package com.mac.hosp_pre.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.binarywang.wxpay.bean.notify.WxPayRefundNotifyResult;
import com.mac.hosp_pre.except.ResultCodeEnum;
import com.mac.hosp_pre.except.ServiceException;
import com.mac.hosp_pre.order.entity.PaymentInfo;
import com.mac.hosp_pre.order.entity.RefundInfo;
import com.mac.hosp_pre.order.enums.RefundStatusEnum;
import com.mac.hosp_pre.order.mapper.RefundInfoMapper;
import com.mac.hosp_pre.order.model.req.PaymentReqDto;
import com.mac.hosp_pre.order.model.resp.PaymentRespDto;
import com.mac.hosp_pre.order.model.resp.RefundRespDto;
import com.mac.hosp_pre.order.service.RefundInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;


@Slf4j
@Service
public class RefundInfoServiceImpl extends ServiceImpl<RefundInfoMapper, RefundInfo> implements RefundInfoService {
    @Override
    public RefundRespDto saveRefundInfo(PaymentRespDto paymentInfo) {
        LambdaQueryWrapper<RefundInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RefundInfo::getOrderId,paymentInfo.getOrderId());
        RefundInfo refundInfo = baseMapper.selectOne(wrapper);
        if (refundInfo != null){
            throw new ServiceException(ResultCodeEnum.INTERNAL_SERVER_ERROR.getCode(),"已提交退款申请");
        }
        //添加记录
        refundInfo = new RefundInfo();
        refundInfo.setOrderId(paymentInfo.getOrderId());
        refundInfo.setPaymentType(paymentInfo.getPaymentType());
        refundInfo.setOutTradeNo(paymentInfo.getOutTradeNo());
        refundInfo.setRefundStatus(RefundStatusEnum.UNREFUND.getStatus());
        refundInfo.setSubject(paymentInfo.getSubject());
        refundInfo.setTotalAmount(paymentInfo.getTotalAmount());
        baseMapper.insert(refundInfo);
        RefundRespDto respDto = new RefundRespDto();
        BeanUtils.copyProperties(refundInfo,respDto);
        return respDto;
    }

    @Override
    public void refundSuccess(Long id, WxPayRefundNotifyResult.ReqInfo reqInfo) {
        RefundInfo refundInfo = new RefundInfo();
        refundInfo.setId(id);
        refundInfo.setRefundStatus(RefundStatusEnum.REFUND.getStatus());
        refundInfo.setCallbackTime(LocalDateTime.now());
        refundInfo.setCallbackContent(reqInfo.toString());
        baseMapper.updateById(refundInfo);
    }
}
